package com.example.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.entity.AirLane;
import com.example.entity.Special;
import com.example.entity.TakeoffLand;
import com.example.entity.Work;
import com.example.entity.shape.CirclePoint;
import com.example.entity.shape.PolygonPoint;
import com.example.entity.shape.WayPoint;
import com.example.mapper.AirLaneMapper;
import com.example.mapper.SpecialMapper;
import com.example.mapper.TakeoffLandMapper;
import com.example.mapper.WorkMapper;
import com.example.service.interfaces.AirLaneInterface;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @program: microservice
 * @description:
 * @author: Aprilies
 * @create: 2024-09-10 16:51
 **/

@Service
public class AirLaneService extends ServiceImpl<AirLaneMapper, AirLane> implements AirLaneInterface {

    @Autowired
    private AirLaneMapper airlaneMapper;
    @Autowired
    private TakeoffLandMapper takeoffLandMapper;
    @Autowired
    private WorkMapper workMapper;
    @Autowired
    private SpecialMapper specialMapper;

    public List<AirLane> findAll(){ return airlaneMapper.selectList(null); }
    public Optional<AirLane> findByID(Long id){return Optional.ofNullable(airlaneMapper.selectById(id));}

    public  AirLane isave(AirLane user){
        airlaneMapper.insert(user);
        return user;
    }

    // 只返回更新的字段数据
    public Optional<AirLane> update(AirLane airLane) {
        int i = airlaneMapper.updateById(airLane);
        if(i == 1){
            return Optional.of(airLane);
        }
        return Optional.empty();
    }

    // 返回所有字段数据
    public Optional<AirLane> update2(Integer id, AirLane airLane) {
        AirLane originairlane = airlaneMapper.selectById(id);
        if (airLane.getStartStopState() != null) {
            originairlane.setAirLaneType(airLane.getStartStopState());
        }
        if (airLane.getCorrespondingTimePeriod() != null) {
            originairlane.setCorrespondingTimePeriod(airLane.getCorrespondingTimePeriod());
        }
        if (airLane.getCapacityThreshold() != null) {
            originairlane.setCapacityThreshold(airLane.getCapacityThreshold());
        }
        if (airLane.getSafeIntervalThreshold() != null) {
            originairlane.setSafeIntervalThreshold(airLane.getSafeIntervalThreshold());
        }
        int i = airlaneMapper.updateById(originairlane);
        if(i == 1){
            return Optional.of(originairlane);
        }
        return Optional.empty();
    }

    public Optional<AirLane> updateParam(Integer id,
                                         String startStopState,
                                         String correspondingTimePeriod,
                                         Float capacityThreshold,
                                         Float safeIntervalThreshold) {

        // 验证ID是否有效
        if (id == null || id <= 0) {
            return Optional.empty();
        }
        // 创建查询条件
        QueryWrapper<AirLane> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        // 创建要更新的对象实例，只返回更新字段
//        AirLane airLane = new AirLane();
        AirLane airLane = airlaneMapper.selectById(id);
        // 根据提供的参数更新字段
        if (startStopState != null) {
            airLane.setStartStopState(startStopState);
        }
        if (capacityThreshold != null) {
            airLane.setCorrespondingTimePeriod(correspondingTimePeriod);
        }
        if (capacityThreshold != null) {
            airLane.setCapacityThreshold(capacityThreshold);
        }
        if (safeIntervalThreshold != null) {
            airLane.setSafeIntervalThreshold(safeIntervalThreshold);
        }
        // 执行更新操作
        int result = airlaneMapper.update(airLane, queryWrapper);

        // 检查更新是否成功
        if (result > 0) {
            return Optional.of(airLane);
        } else {
            return Optional.empty();
        }
    }


    public boolean delete(Long id) {
        if (airlaneMapper.selectById(id) != null) {
            airlaneMapper.deleteById(id);
            return true;
        }
        return false;
    }

    public List<AirLane> searchsorted (String keyword, String sortedField, Boolean sortedOrder){
        QueryWrapper<AirLane> queryWrapper = new QueryWrapper<>();
        if (keyword != null) {
            queryWrapper.like("airspace_object_name", keyword).or()
            .like("id", keyword);
        }
        if (sortedOrder) {
            queryWrapper.orderByAsc(sortedField);
        }
        else {
            queryWrapper.orderByDesc(sortedField);
        }
        List<AirLane> airLanes = airlaneMapper.selectList(queryWrapper);
        return airLanes;
    }

    public List<Object> searchsorted2 (String keyword, String sortedField, Boolean sortedOrder){
        List<Object> result = new ArrayList<>();
        QueryWrapper<AirLane> queryWrapper1 = new QueryWrapper<>();
        if (keyword != null) {
            queryWrapper1.like("airspace_object_name", keyword).or()
                    .like("id", keyword);
        }
        if (sortedOrder) {
            queryWrapper1.orderByAsc(sortedField);
        }
        else {
            queryWrapper1.orderByDesc(sortedField);
        }
        List<AirLane> airLanes = airlaneMapper.selectList(queryWrapper1);

        // 解析每个 AirLane 的 shape 字段
        for (AirLane airLane : airLanes) {
            if (airLane.getShape() != null && !airLane.getShape().isEmpty()) {
                // 使用 FastJSON 解析 shape JSON 字符串为 WayPoint 数组
                List<WayPoint> waypoints = JSON.parseArray(airLane.getShape(), WayPoint.class);
                airLane.setShapeObj(waypoints);  // 将解析结果赋值给 shapeObj
            }
        }

        result.addAll(airLanes);

        QueryWrapper<TakeoffLand> queryWrapper2 = new QueryWrapper<>();
        if(keyword != null){
            queryWrapper2.like("airspace_object_name", keyword).or()
                    .like("id", keyword);
        }
        if (sortedOrder) {
            queryWrapper2.orderByAsc(sortedField);
        }
        else {
            queryWrapper2.orderByDesc(sortedField);
        }
        List<TakeoffLand> takeoffLands = takeoffLandMapper.selectList(queryWrapper2);
        // 解析 TakeoffLand 的 circle_shape 和 polygon_shape
        for (TakeoffLand takeoffLand : takeoffLands) {
            if (takeoffLand.getCircleShape() != null && !takeoffLand.getCircleShape().isEmpty()) {
                List<CirclePoint> circlePoints = JSON.parseArray(takeoffLand.getCircleShape(), CirclePoint.class);
                takeoffLand.setCircleShapeObj(circlePoints);
            }
            if (takeoffLand.getPolygonShape() != null && !takeoffLand.getPolygonShape().isEmpty()) {
                List<PolygonPoint> polygonPoints = JSON.parseArray(takeoffLand.getPolygonShape(), PolygonPoint.class);
                takeoffLand.setPolygonShapeObj(polygonPoints);
            }
        }
        result.addAll(takeoffLands);

        QueryWrapper<Work> queryWrapper3 = new QueryWrapper<>();
        if (keyword != null) {
            queryWrapper3.like("airspace_object_name", keyword).or()
                    .like("id", keyword);
        }
        if (sortedOrder) {
            queryWrapper3.orderByAsc(sortedField);
        }
        else {
            queryWrapper3.orderByDesc(sortedField);
        }
        List<Work> works = workMapper.selectList(queryWrapper3);

        // 解析 Work 的 circle_shape 和 polygon_shape
        for (Work work : works) {
            if (work.getCircleShape() != null && !work.getCircleShape().isEmpty()) {
                List<CirclePoint> circlePoints = JSON.parseArray(work.getCircleShape(), CirclePoint.class);
                work.setCircleShapeObj(circlePoints);
            }
            if (work.getPolygonShape() != null && !work.getPolygonShape().isEmpty()) {
                List<PolygonPoint> polygonPoints = JSON.parseArray(work.getPolygonShape(), PolygonPoint.class);
                work.setPolygonShapeObj(polygonPoints);
            }
        }

        result.addAll(works);

        QueryWrapper<Special> queryWrapper4 = new QueryWrapper<>();
        if (keyword != null) {
            queryWrapper4.like("airspace_object_name", keyword).or()
                    .like("id", keyword);
        }
        if (sortedOrder) {
            queryWrapper4.orderByAsc(sortedField);
        }
        else {
            queryWrapper4.orderByDesc(sortedField);
        }
        List<Special> specials = specialMapper.selectList(queryWrapper4);
        // 解析 Special 的 circle_shape 和 polygon_shape
        for (Special special : specials) {
            if (special.getCircleShape() != null && !special.getCircleShape().isEmpty()) {
                List<CirclePoint> circlePoints = JSON.parseArray(special.getCircleShape(), CirclePoint.class);
                special.setCircleShapeObj(circlePoints);
            }
            if (special.getPolygonShape() != null && !special.getPolygonShape().isEmpty()) {
                List<PolygonPoint> polygonPoints = JSON.parseArray(special.getPolygonShape(), PolygonPoint.class);
                special.setPolygonShapeObj(polygonPoints);
            }
        }
        result.addAll(specials);
        return result;
    }

    public Optional<?> updateall(String tablename, Integer id,
                                  String startstopstate, String correspondingtimeperiod,
                                  Float capacitythreshold, Float safeintervalthreshold){
        if (id == null || id <= 0 || tablename == null) {
            return Optional.empty();
        }

        if (tablename.contains("空域")){
            return updateAirLane(id, startstopstate, correspondingtimeperiod, capacitythreshold, safeintervalthreshold);
        }else if (tablename.contains("起降")){
            return updateTakeoffLand(id, startstopstate, correspondingtimeperiod, capacitythreshold, safeintervalthreshold);
        }else if (tablename.contains("作业")){
            return updateWork(id, startstopstate, correspondingtimeperiod, capacitythreshold, safeintervalthreshold);
        }else {
            return Optional.empty();
        }
    }

    private Optional<AirLane> updateAirLane(Integer id,
                                            String startstopstate,
                                            String correspondingtimeperiod,
                                            Float capacitythreshold,
                                            Float safeintervalthreshold) {
        AirLane airLane = airlaneMapper.selectById(id);
        if(airLane == null){
            return Optional.empty();
        }
        if (startstopstate != null) {
            airLane.setStartStopState(startstopstate);
        }
        if (correspondingtimeperiod != null) {
            airLane.setCorrespondingTimePeriod(correspondingtimeperiod);
        }
        if (capacitythreshold != null) {
            airLane.setCapacityThreshold(capacitythreshold);
        }
        if (safeintervalthreshold != null) {
            airLane.setSafeIntervalThreshold(safeintervalthreshold);
        }
        int i = airlaneMapper.updateById(airLane);
        return i>0 ? Optional.of(airLane) : Optional.empty();
    }

    private Optional<TakeoffLand> updateTakeoffLand(Integer id,
                                            String startstopstate,
                                            String correspondingtimeperiod,
                                            Float capacitythreshold,
                                            Float safeintervalthreshold) {
        TakeoffLand takeoffLand = takeoffLandMapper.selectById(id);
        if(takeoffLand == null){
            return Optional.empty();
        }
        if (startstopstate != null) {
            takeoffLand.setStartStopState(startstopstate);
        }
        if (correspondingtimeperiod != null) {
            takeoffLand.setCorrespondingTimePeriod(correspondingtimeperiod);
        }
        if (capacitythreshold != null) {
            takeoffLand.setCapacityThreshold(capacitythreshold);
        }
        if (safeintervalthreshold != null) {
            takeoffLand.setSafeIntervalThreshold(safeintervalthreshold);
        }
        int i = takeoffLandMapper.updateById(takeoffLand);
        return i>0 ? Optional.of(takeoffLand) : Optional.empty();
    }

    private Optional<Work> updateWork(Integer id,
                                                    String startstopstate,
                                                    String correspondingtimeperiod,
                                                    Float capacitythreshold,
                                                    Float safeintervalthreshold) {
        Work work = workMapper.selectById(id);
        if(work == null){
            return Optional.empty();
        }
        if (startstopstate != null) {
            work.setStartStopState(startstopstate);
        }
        if (correspondingtimeperiod != null) {
            work.setCorrespondingTimePeriod(correspondingtimeperiod);
        }
        if (capacitythreshold != null) {
            work.setCapacityThreshold(capacitythreshold);
        }
        if (safeintervalthreshold != null) {
            work.setSafeIntervalThreshold(safeintervalthreshold);
        }
        int i = workMapper.updateById(work);
        return i>0 ? Optional.of(work) : Optional.empty();
    }

//    public MicroPage<AirLane> page(int current, int size, AirLane condition) {
//        QueryWrapper<AirLane> wrapper = new QueryWrapper<>();
//        if(condition != null && condition.getAircraftType() != null){
//            wrapper.like("application_id", condition.getAircraftType());
//        }
//        Page<AirLane> page = new Page<>(current, size);
//        Page<AirLane> AirLanePage = airlaneMapper.selectPage(page, wrapper);
//        int total = (int)AirLanePage.getTotal();
//        int pageSize = (int)page.getSize();
//        MicroPage<AirLane> AirLaneMicroPage = new MicroPage<>();
//        AirLaneMicroPage.setTotal(total);
//        AirLaneMicroPage.setPageData(AirLanePage.getRecords());
//        AirLaneMicroPage.setPageNum(current);
//        AirLaneMicroPage.setPageSize(size);
//        Integer pages = (int) Math.ceil((double) total / pageSize);
//        AirLaneMicroPage.setPages(pages);
//        return AirLaneMicroPage;
//    }
}
